﻿using System;
using System.Windows;
using Microsoft.Phone.Controls;
using WindowsPhoneAudioStreaming.Audio.Streaming;
using Samples.Radio.Pages.Main;
using Samples.Radio.Pages.Program;
using Samples.Radio.Pages.ProgramList;
using Samples.Radio.Pages.Settings;

namespace Samples.Radio.Data
{
    public class ViewModelLocator
    {
        private ConfigurationSetup configuration;
        public ConfigurationSetup Configuration
        {
            get { return configuration; }
            set
            {
                configuration = value;
                Repository.Configuration = value;
            }
        }

        public RadioRepository Repository { get; private set; }
        public IDispatcher Dispatcher { get; protected set; }
        public INavigation Navigation { get; protected set; }


        public ViewModelLocator()
        {
            Repository = new RadioRepository();
            Dispatcher = Application.Current.RootVisual.Dispatcher.AsInterface();

        }

        public T CreateViewModel<T>() where T : ViewModelBase
        {
            if (Navigation == null)
            {
                var prop = Application.Current.GetType().GetProperty("RootFrame");
                if (prop != null)
                {
                    var frame = prop.GetValue(Application.Current, null) as PhoneApplicationFrame;
                    Navigation = frame.AsInterface();
                }
            }
            var vm = Activator.CreateInstance(typeof(T), Repository, Dispatcher, Navigation) as ViewModelBase;
            return vm as T;
        }

        public MainPageViewModel Main { get { return CreateViewModel<MainPageViewModel>(); } }
        public ProgramPageViewModel Program { get { return CreateViewModel<ProgramPageViewModel>(); } }
        public PodcastPageViewModel Podcast { get { return CreateViewModel<PodcastPageViewModel>(); } }
        public ProgramListPageViewModel ProgramList { get { return CreateViewModel<ProgramListPageViewModel>(); } }
        public SettingsPageViewModel Settings { get { return CreateViewModel<SettingsPageViewModel>(); } }
    }
}
